package com.gitee.maskit.beans.autoconfigure;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.DependencyDescriptor;
import org.springframework.beans.factory.support.AutowireCandidateResolver;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.ContextAnnotationAutowireCandidateResolver;

public class StickyBeanResolver extends ContextAnnotationAutowireCandidateResolver implements BeanFactoryPostProcessor {

    private ContextAnnotationAutowireCandidateResolver resolver;

    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        if (beanFactory instanceof DefaultListableBeanFactory) {
            AutowireCandidateResolver acr = ((DefaultListableBeanFactory) beanFactory).getAutowireCandidateResolver();
            if (!(acr instanceof StickyBeanResolver) && acr instanceof ContextAnnotationAutowireCandidateResolver) {
                this.resolver = (ContextAnnotationAutowireCandidateResolver)
                    ((DefaultListableBeanFactory) beanFactory).getAutowireCandidateResolver();
                ((DefaultListableBeanFactory) beanFactory).setAutowireCandidateResolver(this);
            }
        } else {
            throw new IllegalStateException("Database accessing objects can't be injected automatically for "
                + beanFactory.getClass().getName() + " is not a instance of " + DefaultListableBeanFactory.class);
        }
    }

    @Override
    public boolean isAutowireCandidate(BeanDefinitionHolder bdHolder, DependencyDescriptor descriptor) {
        boolean isCandidate = super.isAutowireCandidate(bdHolder, descriptor);
        if (isCandidate && null != resolver && null != bdHolder.getBeanDefinition().getSource()) {
        }
        return isCandidate;
    }
}
